<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智能客服助手</title>
    <style>
      body {
        font-family: "Arial", sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
      }
      #chat-container {
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        overflow: hidden;
      }
      #chat-box {
        height: 500px;
        padding: 20px;
        overflow-y: auto;
      }
      .message {
        margin-bottom: 15px;
        padding: 10px 15px;
        border-radius: 18px;
        max-width: 70%;
        word-wrap: break-word;
      }
      .user-message {
        background: #007bff;
        color: white;
        margin-left: auto;
      }
      .bot-message {
        background: #e9ecef;
        color: black;
        margin-right: auto;
      }
      #input-area {
        display: flex;
        padding: 15px;
        background: #f8f9fa;
        border-top: 1px solid #ddd;
      }
      #user-input {
        flex: 1;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 20px;
        outline: none;
      }
      #send-button {
        margin-left: 10px;
        padding: 10px 20px;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 20px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="chat-container">
      <div id="chat-box"></div>
      <div id="input-area">
        <input type="text" id="user-input" placeholder="输入消息..." />
        <button id="send-button">发送</button>
      </div>
    </div>

    <script>
      const chatBox = document.getElementById("chat-box");
      const userInput = document.getElementById("user-input");

      function addMessage(role, content) {
        const messageDiv = document.createElement("div");
        messageDiv.classList.add("message", `${role}-message`);
        messageDiv.textContent = content;
        chatBox.appendChild(messageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;
      }

      document
        .getElementById("send-button")
        .addEventListener("click", sendMessage);
      userInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") sendMessage();
      });

      function sendMessage() {
        const message = userInput.value.trim();
        if (!message) return;

        addMessage("user", message);
        userInput.value = "";

        // 创建机器人消息容器
        const botMessageDiv = document.createElement("div");
        botMessageDiv.classList.add("message", "bot-message");
        chatBox.appendChild(botMessageDiv);
        chatBox.scrollTop = chatBox.scrollHeight;

        // 使用fetch方法发送POST请求并处理SSE流
        fetch("/chat", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ message: message }),
        })
          .then((response) => {
            if (!response.ok) {
              throw new Error("网络响应不正常: " + response.statusText);
            }
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = "";

            function processText({ done, value }) {
              if (done) {
                return;
              }

              buffer += decoder.decode(value, { stream: true });
              const lines = buffer.split("\n\n");
              buffer = lines.pop() || "";

              for (const line of lines) {
                if (line.startsWith("data: ")) {
                  const data = line.slice(6);
                  if (data === "[DONE]") {
                    return reader.cancel();
                  }
                  try {
                    const json = JSON.parse(data);
                    if (json.message) {
                      botMessageDiv.textContent += json.message;
                      chatBox.scrollTop = chatBox.scrollHeight;
                    }
                    if (json.error) {
                      botMessageDiv.textContent += "\n错误: " + json.error;
                    }
                  } catch (e) {
                    console.error("解析SSE数据失败:", e);
                  }
                }
              }

              return reader.read().then(processText);
            }

            return reader.read().then(processText);
          })
          .catch((error) => {
            botMessageDiv.textContent =
              "获取响应时出错: " + error.message + "\n(对话结束)";
          });
      }
    </script>
  </body>
</html>
